package com.example.ocridentification.service;

import com.example.ocridentification.config.ImageToBase64;
import com.example.ocridentification.model.IdentityBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class IdentityService {
    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private ObjectMapper objectMapper;

    private String cardPath = "D:\\image\\card1.jpg";

    private String appcode = "c8518f45d5334300b73c638e299820ab";

    public String getIdentityData() throws IOException {
        IdentityBody identityBody = new IdentityBody();
        identityBody.image = ImageToBase64.imageToBase64(cardPath);
        RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(identityBody),
                MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url("https://cardnumber.market.alicloudapi.com/rest/160601/ocr/ocr_idcard.json")
                .addHeader("Authorization", "APPCODE " + appcode)
                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .post(requestBody)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                String errorBody = response.body().string();
                throw new IOException(
                        "API请求失败:\n" +
                                "状态码: " + response.code() + "\n" +
                                "错误信息: " + response.message() + "\n" +
                                "响应体: " + errorBody
                );
            }

            String ret = response.body().string();
            System.out.println("识别结果: " + ret);
            return ret;
        }
    }
}
